package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.service.TransferService;

/**
 * 转账service
 */
public class TransferServiceImpl implements TransferService {

    // 问题1: new关键字将service层的实现类TransferServiceImpl和DAO层的实现类JdbcAccountDaoImpl耦合
    // private AccountDao accountDao = new JdbcAccountDaoImpl();
    // 方法1: 使用工厂,通过反射技术实例化对象
    // private AccountDao accountDao = (AccountDao) BeanFactory.getBean("accountDao");
    // 方法2: 最佳状态
    private AccountDao accountDao;
    // 构造函数传值/set方法传值
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
        // 问题2: service层没有添加事务控制,可能会导致数据错乱
        // 问题3: 事务可提取
        /*
        try{
            // 开启事务(关闭事务的自动提交)
            ConnectionUtils.getInstance().getCurrentThreadConn().setAutoCommit(false);
            // 把事务操作封装为事务管理类TransactionManager
            TransactionManager.getInstance().beginTransaction();
        */
            Account from = accountDao.queryAccountByCardNo(fromCardNo);
            Account to = accountDao.queryAccountByCardNo(toCardNo);
            from.setMoney(from.getMoney()-money);
            to.setMoney(to.getMoney()+money);
            accountDao.updateAccountByCardNo(to);
            int c = 1/0;    // 制造异常
            accountDao.updateAccountByCardNo(from);
        /*
            // 提交事务
            ConnectionUtils.getInstance().getCurrentThreadConn().commit();
            TransactionManager.getInstance().commit();
        }catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
            ConnectionUtils.getInstance().getCurrentThreadConn().rollback();
            TransactionManager.getInstance().rollback();
            // 抛出异常便于上层servlet捕获
            throw e;
        }
        */
    }
}
